import router, { asyncRoutes } from '@/router'
import store from '@/store'
// console.log(router.options.routes)
// 进度条效果
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
const whiteList = ['/login', '/404']
// 前置守卫
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  if (token) {
    // 保证只会拿一次
    if (!store.state.user.userInfo.id) {
      const { roles: { menus }} = await store.dispatch('user/getInfo')
      const arr = asyncRoutes.filter(item => menus.includes(item.name))
      router.addRoutes([...arr, { path: '*', redirect: '/404', hidden: true }])
      store.commit('permission/setRoutes', arr)
      next(to.path)
    }
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})
// 后置守卫
router.afterEach((to, from, next) => {
  if (to.meta.title) {
    document.title = '人力资源管理系统-' + to.meta.title
  } else {
    document.title = '人力资源管理系统'
  }

  NProgress.done()
})

